<?php

namespace app\miniprogram\controller;

use app\common\tool\Wechat;
use app\common\storage;
use app\miniprogram\validate\Login as Validate;

/**
 * 首页接口
 */
class Login extends Base
{
    protected $noNeedLogin = ['*'];

    /**
     * 小程序code 登录
     *
     */
    public function index()
    {
        $post = $this->request->post();
        $validate = Validate::factory();
        if(!$validate->scene('login')->check($post)) {
            $this->error($validate->getError());
        }
        $code = $post['code'];
        $app = Wechat::miniprogram();
        $result = $app->auth->session($code);

        if(!$validate->scene('get_token')->check($result)) {
            $this->error($validate->getError(), $result);
        }
        $login = $this->get_login();
        $token = $login->get_token($result);
        $user = $login->getCurrentUser($token);
        $user['token'] = $token;
        $this->success('', $user);
    }

    /**
     * 获取用户手机号
     */
    public function phone() {
        $post = $this->request->post();
        $login = $this->get_login();
        $options = $login->token2options();

        if(is_array($options)) {
            $post = array_merge($post, $options);
        }
        $validate = Validate::factory();
        if(!$validate->scene('phone')->check($post)) {
            $this->no_login($validate->getError());
        }
        $encryptedData = $post['encrypted_data'];
        $iv = $post['iv'];
        $sessionKey = $options['session_key'];
        
        $app = Wechat::miniprogram();
        $user = $login->getCurrentUser();

        $result = $app->encryptor->decryptData($sessionKey, $iv, $encryptedData);
        if(!$validate->scene('encrypted_data')->check($result)) {
            $this->no_login($validate->getError());
        }

        $phone = $result['purePhoneNumber'];
        if($user) {
            $arr = ['phone' => $phone];
            $user->save($arr);
        } else {
            $login->create4phone($phone);
            $user = $login->getCurrentUser();
        }
        $this->success('', $user);
    }

    public function is_ruzhu() {
        $this->success('', 1);
    }
}
